package singleton;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ConcurrencyTester;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 懒汉式
 * @Date: Created in 2021/12/5 23:14
 */
@Slf4j
public class SingletonTwo {

    private static SingletonTwo SINGLETON_THREE = null;

    private SingletonTwo() {
        log.info("加载数据");
    }

    /**
     * 无<code>synchronized</code>时，是线程不安全的，但会延迟加载
     * 有<code>synchronized</code>时，是线程安全的，会延迟加载
     *
     * @return
     */
    public static synchronized SingletonTwo getInstance() {
        if (Objects.isNull(SINGLETON_THREE)) {
            SINGLETON_THREE = new SingletonTwo();
        }
        return SINGLETON_THREE;
    }

    public String getDate() {
        return DateUtil.now();
    }


    public static void main(String[] args) {
        ConcurrencyTester concurrencyTester = new ConcurrencyTester(100);
        concurrencyTester.test(() -> {
            SingletonTwo instance = SingletonTwo.getInstance();
            instance.getDate();
        });
        System.out.println(concurrencyTester.getInterval());
    }
}
